<template>
    <el-card style="height: 80px;">
        <el-form :inline="true" class="form">
            <el-form-item label="职位搜索：">
                <el-input placeholder="请输入职位名" v-model="keyword"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :disabled="!keyword" @click="search">搜索</el-button>
                <el-button type="primary" plain @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin: 10px 0;">
        <el-button type="primary" @click="addRole">添加职位</el-button>
        <!-- table展示用户信息 -->
        <el-table border style="margin: 10px 0" :data="allRole">
            <el-table-column label="#" type="index" align="center"></el-table-column>
            <el-table-column label="ID" align="center" prop="id"></el-table-column>
            <el-table-column label="角色名称" align="center" prop="roleName" show-overflow-tooltip></el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip></el-table-column>
            <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="300px" align="center">
                <template #="{ row }">
                    <el-button type="primary" size="small" icon="User" @click="setPermission(row)">分配权限</el-button>
                    <el-button type="success" size="small" icon="Edit" @click="updateRole(row)">编辑</el-button>
                    <el-popconfirm :title="`你确定要删除${row.roleName}?`" width="260px" @confirm="removeRole(row.id)">
                        <template #reference>
                            <el-button type="danger" size="small" icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
            :background="true" layout="prev, pager, next, jumper,->,sizes,total" :total="total"
            @size-change="sizeChange" @current-change="getHasRole" />
    </el-card>
    <!-- 添加与更新职位 -->
    <el-dialog v-model="dialogVisible" :title="roleParams.id ? '编辑职位' : '添加职位'">
        <el-form :model="roleParams" :rules="rules" ref="form">
            <el-form-item label="职位名称：" prop="roleName">
                <el-input placeholder="请输入职位名" v-model="roleParams.roleName"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="save">确认</el-button>
        </template>
    </el-dialog>
    <!-- 抽屉分配职位信息 -->
    <el-drawer v-model="drawer">
        <template #header>
            <h4>分配职位的权限</h4>
        </template>
        <template #default>
            <el-tree ref="tree" style="max-width: 600px" :data="menuArr" show-checkbox node-key="id" default-expand-all
                :default-checked-keys="selectArr" :props="defaultProps" />
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer = false">取消</el-button>
                <el-button type="primary" @click="handler">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { reqAllRoleList, reqAddOrUpdateRole, reqAllMenuList, reqPermission, reqRemoveRole } from '@/api/acl/role'
import type { RoleData, RoleResponseData, Records, MenuResponseData, MenuList } from '@/api/acl/role/type';
import useLayOutSettingStore from '@/stores/modules/setting';
//获取模板setting仓库
const settingStore = useLayOutSettingStore()
// 分页器数据
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(0)
// 搜索职位的关键字
let keyword = ref<string>('')
//存储全部已有的职位
let allRole = ref<Records>([]);
// 控制对话框显示隐藏
let dialogVisible = ref<boolean>(false)
// 收集新增岗位
let roleParams = reactive<RoleData>({
    roleName: ''
})
// 控制抽屉的显示
let drawer = ref<boolean>(false)
let menuArr = ref<MenuList>([])
//准备一个数组:数组用于存储勾选的节点的ID(四级的)
let selectArr = ref<number[]>([]);
let form = ref()
// 获取树形控件的实例
let tree = ref()
//自定义校验规则的回调
const validatorRoleName = (rule: any, value: any, callBack: any) => {
    if (value.trim().length >= 2) {
        callBack();
    } else {
        callBack(new Error('职位名称至少两位'))
    }
}
//职位校验规则
const rules = {
    roleName: [
        { required: true, trigger: 'blur', validator: validatorRoleName }
    ]
}
// 组件挂在完毕请求已有数据
onMounted(() => {
    getHasRole()
})
// 获取已有数据
const getHasRole = async (pager = 1) => {
    pageNo.value = pager
    let result: RoleResponseData = await reqAllRoleList(pageNo.value, pageSize.value, keyword.value)
    if (result.code == 200) {
        total.value = result.data.total;
        allRole.value = result.data.records;
    }
}
// 下拉菜单修改
const sizeChange = () => {
    getHasRole()
}
// 搜索
const search = () => {
    getHasRole()
    keyword.value = ''
}
// 重置按钮
const reset = () => {
    settingStore.refsh = !settingStore.refsh
}
// 添加职位
const addRole = () => {
    dialogVisible.value = true
    // 清空校验规则
    Object.assign(roleParams, {
        roleName: '',
        id: 0
    })
    //清空上一次表单校验错误结果
    nextTick(() => {
        form.value.clearValidate('roleName');
    })
}
// 更新已有的职位
const updateRole = (row: RoleData) => {
    dialogVisible.value = true
    // 存储已有的数据，带有ID
    Object.assign(roleParams, row)
    // 清校验结果
    nextTick(() => {
        form.value.clearValidate('roleName');
    })
}
// 确认更新或者编辑
const save = async () => {
    //表单校验结果,结果通过在发请求、结果没有通过不应该在发生请求
    await form.value.validate();
    //添加职位|更新职位的请求
    let result: any = await reqAddOrUpdateRole(roleParams);
    if (result.code == 200) {
        //提示文字
        ElMessage({ type: 'success', message: roleParams.id ? '更新成功' : '添加成功' });
        //对话框显示
        dialogVisible.value = false;
        //再次获取全部的已有的职位
        getHasRole(roleParams.id ? pageNo.value : 1);
    }
}
// 分配权限按钮
const setPermission = async (row: RoleData) => {
    // 显示抽屉
    drawer.value = true
    Object.assign(roleParams, row)
    let result: MenuResponseData = await reqAllMenuList(roleParams.id as number)
    if (result.code = 200) {
        menuArr.value = result.data
        selectArr.value = filterSelectArr(menuArr.value, [])
    }
}
//树形控件的测试数据
const defaultProps = {
    children: 'children',
    label: 'name',
}
const filterSelectArr = (allData: any, initArr: any) => {
    allData.forEach((item: any) => {
        if (item.select && item.level == 4) {
            initArr.push(item.id)
        }
        if (item.children && item.children.length > 0) {
            filterSelectArr(item.children, initArr)
        }
    });
    return initArr
}
// 抽屉确定按钮
const handler = async () => {
    // 职位的ID
    const roleId = roleParams.id as number
    // 选中节点的ID 
    let arr = tree.value.getCheckedKeys()
    // 半选的ID
    let arr1 = tree.value.getHalfCheckedKeys()
    let permission = arr.concat(arr1)
    // 下发权限
    let result: any = await reqPermission(roleId, permission)
    if (result.code == 200) {
        //抽屉关闭
        drawer.value = false;
        //提示信息
        ElMessage({ type: 'success', message: '分配权限成功' });
        //页面刷新
        window.location.reload();
    }
}
//删除已有的职位
const removeRole = async (id: number) => {
    let result: any = await reqRemoveRole(id);
    if (result.code == 200) {
        //提示信息
        ElMessage({ type: 'success', message: '删除成功' });
        getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1);
    }
}
</script>
<style lang="scss" scoped>
.form {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>